<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>我的病历</title>
    <link rel="stylesheet" href="css/myMedicalRecords.css">
    <script src="js/jquery.min.js"></script>
</head>
<body>
<div class="main-wrapper">
    <div class="sidebar">
        <h3>医院病例管理系统</h3>
        <ul>
            <li><a href="./personalInfo.html">个人信息</a></li>
            <li><a href="./myMedicalRecords.html" class="active">我的病历</a></li>
            <li><a href="./registerAppointment.html">在线挂号</a></li>
        </ul>
    </div>
    <div class="main-content">
        <div class="info-card">
            <h2>我的病历</h2>
            <div class="search-input-container">
                <input type="text" class="form-control" id="searchInput" placeholder="搜索病历...">
            </div>
            <table class="medical-records-table">
                <thead>
                    <tr>
                        <th>挂号ID</th>
                        <th>医生姓名</th>
                        <th>诊断结果</th>
                        <th>日期</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="medicalRecordsTableBody">
                    <!-- 病历数据将在这里加载 -->
                </tbody>
            </table>
            <div id="medicalRecordsLoading" class="loading-message" style="display: none;">加载中...</div>
            <div id="medicalRecordsError" class="error-message" style="display: none;">加载失败</div>
            <nav aria-label="Page navigation">
                <ul class="pagination" id="pagination">
                    <!-- 分页控件将在这里动态加载 -->
                </ul>
            </nav>
        </div>
    </div>
</div>

<!-- 病历详情模态框 -->
<div id="medicalRecordDetailModal" class="modal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body"></div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-primary" id="downloadMedicalRecordBtn">下载/打印</button>
      </div>
    </div>
  </div>
</div>

<script>
$(function(){
    let allRecords = [];
    const backendBaseUrl = 'http://localhost:8080'; // 确保使用完整的后端 URL

    function renderTable(records) {
        const $tbody = $('#medicalRecordsTableBody');
        $tbody.empty();
        if (records.length === 0) {
            $tbody.append('<tr><td colspan="5" class="text-center">暂无病历记录</td></tr>');
            return;
        }
        records.forEach(record => {
            const $row = $('<tr>');
            $row.append($('<td>').text(record.registerId));
            $row.append($('<td>').text(record.doctorUsername || '-'));
            $row.append($('<td>').text(record.diagnosis || '-'));
            $row.append($('<td>').text( new Date( record.registerTime).toLocaleString()));
            const $viewButton = $('<button>')
                .addClass('btn view-medical-record-btn') // 移除 Bootstrap btn-sm btn-info me-2
                .text('查看详情')
                .attr('data-id', record.id);
            const $actionsCell = $('<td>').append($viewButton);
            $row.append($actionsCell);
            $tbody.append($row);
        });
    }

    function loadMedicalRecords() {
        $('#medicalRecordsLoading').show();
        $('#medicalRecordsError').hide();
        $('#medicalRecordsTableBody').empty();
        $.ajax({
            url: backendBaseUrl + '/medical/user/list', // 使用完整的后端 URL
            type: 'GET',
            xhrFields: { withCredentials: true }, // 确保携带 cookie
            success: function(res) {
                $('#medicalRecordsLoading').hide();
                if (res.code === 0 && res.data) {
                    allRecords = res.data;
                    renderTable(allRecords);
                    // TODO: Add pagination rendering logic here if needed
                } else {
                    $('#medicalRecordsError').text(res.message || '获取病历列表失败').show();
                }
            },
            error: function() {
                $('#medicalRecordsLoading').hide();
                $('#medicalRecordsError').text('请求失败，请稍后重试').show();
            }
        });
    }

    $('#searchInput').on('input', function(){
        const keyword = $(this).val().trim().toLowerCase();
        const filtered = allRecords.filter(record =>
            (record.diagnosis && record.diagnosis.toLowerCase().includes(keyword)) ||
            (record.doctorUsername && record.doctorUsername.toLowerCase().includes(keyword)) ||
            (record.registerId && String(record.registerId).includes(keyword))
        );
        renderTable(filtered);
    });

    $('#medicalRecordsTableBody').on('click', '.view-medical-record-btn', function(){
        const recordId = $(this).data('id');
        if (!recordId) return;
        $.ajax({
            url: backendBaseUrl + '/medical/user/' + recordId, // 使用完整的后端 URL
            type: 'GET',
            xhrFields: { withCredentials: true }, // 确保携带 cookie
            success: function(res) {
                if (res.code === 0 && res.data) {
                    const record = res.data;
                    console.log('Record:', record);
                    let html = '';
                    html += '<strong>挂号ID：</strong>' + (record.registerId || '-') + '<br>';
                    html += '<strong>医生姓名：</strong>' + (record.doctorUsername || '-') + '<br>';
                    html += '<strong>挂号时间：</strong>' + (new Date(record.registerTime).toLocaleString() || '-') + '<br>';
                    html += '<strong>主诉：</strong>' + (record.readme || '-') + '<br>';
                    html += '<strong>现病史：</strong>' + (record.present || '-') + '<br>';
                    html += '<strong>现病治疗情况：</strong>' + (record.presentTreat || '-') + '<br>';
                    html += '<strong>既往史：</strong>' + (record.history || '-') + '<br>';
                    html += '<strong>过敏史：</strong>' + (record.allergy || '-') + '<br>';
                    html += '<strong>体格检查：</strong>' + (record.physique || '-') + '<br>';
                    html += '<strong>检查/检验建议：</strong>' + (record.proposal || '-') + '<br>';
                    html += '<strong>注意事项：</strong>' + (record.careful || '-') + '<br>';
                    html += '<strong>诊断结果：</strong>' + (record.diagnosis || '-') + '<br>';
                    html += '<strong>处理意见：</strong>' + (record.cure || '-') + '<br>';

                    showDetailModal('病历详情', html);
                } else {
                    alert(res.message || '获取病历详情失败');
                }
            },
            error: function() {
                alert('请求失败，请稍后重试');
            }
        });
    });

    function showDetailModal(title, html) {
        const $modal = $('#medicalRecordDetailModal');
        $modal.find('.modal-title').text(title);
        $modal.find('.modal-body').html(html);

        // 绑定下载/打印事件
        $modal.find('#downloadMedicalRecordBtn').off('click').on('click', function() {
            printMedicalRecord(title, html);
        });

        // 使用 jQuery 显示模态框
        $modal.css('display', 'block').addClass('show');
        // 添加点击背景关闭模态框
        $modal.on('click', function(e) {
            if ($(e.target).hasClass('modal')) {
                hideDetailModal();
            }
        });
        // 添加关闭按钮事件
        $modal.find('.close, .btn-secondary').on('click', hideDetailModal);
    }

    function hideDetailModal() {
        const $modal = $('#medicalRecordDetailModal');
        $modal.css('display', 'none').removeClass('show');
        // 移除事件监听，避免重复绑定
        $modal.off('click');
        $modal.find('.close, .btn-secondary').off('click');
    }

    function printMedicalRecord(title, html) {
        const printWindow = window.open('', '', 'height=600,width=800');
        printWindow.document.write('<html><head><title>' + title + '</title>');
        // 可以选择在此处引用一个打印专用的 CSS 文件
        printWindow.document.write('<style>');
        printWindow.document.write('body { font-family: Arial, sans-serif; line-height: 1.6; }');
        printWindow.document.write('h2 { text-align: center; margin-bottom: 20px; }');
        printWindow.document.write('strong { display: inline-block; width: 150px; margin-bottom: 10px; }'); // 示例样式，可调整
        printWindow.document.write('</style>');
        printWindow.document.write('</head><body>');
        printWindow.document.write('<h2>' + title + '</h2>');
        printWindow.document.write('<div>' + html + '</div>');
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        printWindow.focus();
        printWindow.print();
    }

    loadMedicalRecords();
});
</script>
</body>
</html> 